import { ref, reactive } from 'vue'

// 表单显示状态
const showCategoryForm = ref(false)
const showItemForm = ref(false)
const showPageForm = ref(false)
const showRelationForm = ref(false)

// 编辑状态
const editingCategory = ref(null)
const editingItem = ref(null)
const editingPage = ref(null)

// 表单数据模板
const defaultCategoryForm = {
  name: '',
  description: '',
  icon: '',
  parent_id: null,
  status: 1
}

const defaultItemForm = {
  name: '',
  description: '',
  icon: '',
  iconFile: null,
  content_type: 'page',
  api_endpoint: '',
  page_path: '',
  external_url: '',
  component_name: '',
  content: '# 项目内容\n\n请在此处编写项目的详细内容...',
  parent_id: null,
  category_id: null,
  is_small: false,
  params: '',
  display_order: 0,
  status: 1
}

const defaultPageForm = {
  code: '',
  name: '',
  description: '',
  display_order: 0,
  status: 1
}

// 表单数据
const categoryForm = reactive({ ...defaultCategoryForm })
const itemForm = reactive({ ...defaultItemForm })
const pageForm = reactive({ ...defaultPageForm })

// 表单验证规则
const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const itemRules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  icon: [
    { 
      validator: (rule, value, callback) => {
        if (value && value.length > 200) {
          callback(new Error('图标路径长度不能超过200个字符'))
        } else {
          callback()
        }
      }, 
      trigger: ['change', 'blur'] 
    }
  ],
  content_type: [
    { required: true, message: '请选择内容类型', trigger: 'change' }
  ],
  display_order: [
    { type: 'number', message: '显示顺序必须是数字', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const pageRules = {
  code: [
    { required: true, message: '请输入页面代码', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '页面代码只能包含字母、数字、下划线和横线', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入页面名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  display_order: [
    { type: 'number', message: '显示顺序必须是数字', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

export const useFormManager = () => {
  // 重置表单数据
  const resetCategoryForm = () => {
    Object.assign(categoryForm, defaultCategoryForm)
    editingCategory.value = null
  }
  
  const resetItemForm = () => {
    Object.assign(itemForm, defaultItemForm)
    editingItem.value = null
  }
  
  const resetPageForm = () => {
    Object.assign(pageForm, defaultPageForm)
    editingPage.value = null
  }
  
  const resetAllForms = () => {
    resetCategoryForm()
    resetItemForm()
    resetPageForm()
  }
  
  // 打开表单
  const openCategoryForm = (category = null) => {
    if (category) {
      editingCategory.value = category
      Object.assign(categoryForm, { ...category })
    } else {
      resetCategoryForm()
    }
    showCategoryForm.value = true
  }
  
  const openItemForm = (item = null) => {
    if (item) {
      editingItem.value = item
      Object.assign(itemForm, { ...item })
    } else {
      resetItemForm()
    }
    showItemForm.value = true
  }
  
  const openPageForm = (page = null) => {
    console.log('🚨🚨🚨 useFormManager - openPageForm 被调用 🚨🚨🚨')
    console.log('🔍 useFormManager - page:', page)
    
    if (page) {
      editingPage.value = page
      Object.assign(pageForm, { ...page })
      console.log('🔍 useFormManager - 编辑模式，设置 pageForm:', pageForm)
    } else {
      resetPageForm()
      console.log('🔍 useFormManager - 新建模式，重置表单')
    }
    
    console.log('🔍 useFormManager - 设置 showPageForm = true')
    showPageForm.value = true
    console.log('✅ useFormManager - openPageForm 执行完成')
  }
  
  // 关闭表单
  const closeCategoryForm = () => {
    showCategoryForm.value = false
    resetCategoryForm()
  }
  
  const closeItemForm = () => {
    showItemForm.value = false
    resetItemForm()
  }
  
  const closePageForm = () => {
    showPageForm.value = false
    resetPageForm()
  }
  
  const closeAllForms = () => {
    showCategoryForm.value = false
    showItemForm.value = false
    showPageForm.value = false
    showRelationForm.value = false
    resetAllForms()
  }
  
  // 表单验证
  const validateCategoryForm = (formRef) => {
    return new Promise((resolve, reject) => {
      formRef.validate((valid) => {
        if (valid) {
          resolve(true)
        } else {
          reject(new Error('表单验证失败'))
        }
      })
    })
  }
  
  const validateItemForm = (formRef) => {
    return new Promise((resolve, reject) => {
      formRef.validate((valid) => {
        if (valid) {
          resolve(true)
        } else {
          reject(new Error('表单验证失败'))
        }
      })
    })
  }
  
  const validatePageForm = (formRef) => {
    return new Promise((resolve, reject) => {
      formRef.validate((valid) => {
        if (valid) {
          resolve(true)
        } else {
          reject(new Error('表单验证失败'))
        }
      })
    })
  }
  
  // 获取表单数据副本
  const getCategoryFormData = () => ({ ...categoryForm })
  const getItemFormData = () => ({ ...itemForm })
  const getPageFormData = () => ({ ...pageForm })
  
  // 检查是否为编辑模式
  const isEditingCategory = () => editingCategory.value !== null
  const isEditingItem = () => editingItem.value !== null
  const isEditingPage = () => editingPage.value !== null
  
  return {
    // 表单显示状态
    showCategoryForm,
    showItemForm,
    showPageForm,
    showRelationForm,
    
    // 编辑状态
    editingCategory,
    editingItem,
    editingPage,
    
    // 表单数据
    categoryForm,
    itemForm,
    pageForm,
    
    // 验证规则
    categoryRules,
    itemRules,
    pageRules,
    
    // 表单操作方法
    resetCategoryForm,
    resetItemForm,
    resetPageForm,
    resetAllForms,
    
    openCategoryForm,
    openItemForm,
    openPageForm,
    
    closeCategoryForm,
    closeItemForm,
    closePageForm,
    closeAllForms,
    
    // 表单验证
    validateCategoryForm,
    validateItemForm,
    validatePageForm,
    
    // 获取表单数据
    getCategoryFormData,
    getItemFormData,
    getPageFormData,
    
    // 编辑状态检查
    isEditingCategory,
    isEditingItem,
    isEditingPage
  }
}